import os
from time import sleep
import matplotlib.pyplot as plt
import numpy as np
import cv2
from threading import Thread

path = "../01.png"
def adb_cmd(cmd):
    output_date = os.popen(f"adb shell {cmd}")
    print(output_date.read())

#模拟鼠标的点击事件，x，y为点击的坐标
def touch(x, y):
    adb_cmd(f'input tap {x} {y}')

#模拟文字输入事件，text输入字符串
def text(text):
    adb_cmd(f'input text {text}')

#模拟滑动事件，x1,y1为起始坐标,x2,y2为终点坐标，t为滑动的时间
def swipe_num(x1,y1,x2,y2,t,delay_t):
    while(1):
        #t = 1000*t
        global stop_threads
        adb_cmd(f'input touchscreen swipe {x1} {y1} {x2} {y2} {t}')
        sleep(delay_t)
        if stop_threads:
            break
        
#模拟按键事件，3代表回主页按键，4代表返回按键
def keyevent(x):
    adb_cmd(f'input keyevent {x}')

#模拟拖动事件，x1,y1为起始坐标,x2,y2为终点坐标，t为拖动的时间
def draganddrop(x1,y1,x2,y2,t):
    adb_cmd(f'input draganddrop {x1} {y1} {x2} {y2} {t}')

def screen():
    adb_cmd(f'screencap -p /sdcard/01.png')
    sleep(0.1)
    os.popen(f"adb pull /sdcard/01.png ../")
    sleep(3)

screen()
img = cv2.imread(path)     #读取图片
size = img.shape[:2]
n =3
new_width = size[1] // n
new_height = size[0] // n

a = []
b = []

#鼠标点击
def clickAdb(x, y):
    touch(x,y)
    #screen()
    #img = cv2.imread(path )

def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        stop_threads = True  #关闭滑动线程
        a.append(x)
        b.append(y)
        cv2.circle(img, (x, y), 5, (255, 0, 0), thickness=-1)
        cv2.imshow("image", img)
        print("[{},{}]".format(a[-1], b[-1]))	#输出最后一次点击的坐标
        clickAdb(x,y)
        #cv2.waitKey(0.1)
        #cv2.imshow("image", img)
    elif event == cv2.EVENT_MOUSEWHEEL:  # 滚轮
        print("swipe")
        stop_threads = False  #打开滑动线程
        if flags > 0:  # 滚轮上移
           swipe_num(540, 1000, 540,2000,100, 10)
        else:  # 滚轮下移
            
            t1.start()
            

'''
# 回调函数：鼠标点击输出或者模拟滑动
# （事件（鼠标移动、左键、右键），横坐标，纵坐标，组合键，setMouseCallback的userdata用于传参）
def mouse_callback(event, x, y, flags, userdata):
    global start_x, start_y, drawing
    # 鼠标左键单击
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        start_x, start_y = x, y

        if drawing == True:
            cv2.rectangle(img, (start_x, start_y), (x, y), (0, 0, 255), -1)

    # 鼠标左键松开
    elif event == cv2.EVENT_LBUTTONUP:
    # 鼠标移动
    elif event == cv2.EVENT_MOUSEMOVE:
        drawing = False
'''

print("start")


cv2.namedWindow("image", cv2.WINDOW_NORMAL)
cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN)
cv2.resizeWindow("image", new_width, new_height)

stop_threads = False
t1 = Thread(target = swipe_num,args=(540,2000, 540, 1000, 100, 10))
while 1:
    
    cv2.imshow("image", img)
    cv2.waitKey(500)
    print("获取图像")
    screen()
    print("显示图像")
    
    img = cv2.imread(path)
    #sleep(10)
   
    #a = a- 1;


cv2.destroyAllWindows()

